package phone.qyg.com.qyg.activity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.PromptManager;
import com.app.utils.ShareOtherUtils;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.umeng.socialize.ShareAction;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.CollectionItem;
import phone.qyg.com.qyg.model.CultureDetail;
import phone.qyg.com.qyg.model.Roll;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.CultureImageHolderView;

/**
 * 作者：lblbh on 2018/1/12 16:29
 * 邮箱：lanbuhan@163.com
 * 功能：文化超市详情-图片
 */
@ContentView(R.layout.culture_img_detail)
public class CultureImgDetailActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.share)
    TextView share;

    @ViewInject(R.id.chollect)
    TextView chollect;

    @ViewInject(R.id.title)
    TextView title;

    @ViewInject(R.id.time)
    TextView time;

    @ViewInject(R.id.code)
    TextView code;

    @ViewInject(R.id.author)
    TextView author;

    @ViewInject(R.id.type)
    TextView type;

    @ViewInject(R.id.publish)
    TextView publish;

    @ViewInject(R.id.keyword)
    TextView keyword;

    @ViewInject(R.id.item_content)
    TextView item_content;

    @ViewInject(R.id.title_btn)
    TextView title_btn;

    @ViewInject(R.id.info_linear)
    LinearLayout info_linear;

    @ViewInject(R.id.convenientBanner)
    com.app.view.ConvenientBanner convenientBanner;

    ShareAction mShareAction;

    CultureDetail model;

    int total;

    int resId;

    @Override
    public void initSucessView() {
        Object obj = getTransModels();

        if(obj instanceof Base){
            Base base = (Base) obj;
            resId = base.id;
        }else if(obj instanceof CollectionItem){
            CollectionItem item = (CollectionItem) obj;
            resId = item.objectId;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mapKeys.put(AppHttpKey.CULTURE_RES_ID,String.valueOf(resId));

        AppHttpRequest.httpRequestDefalut(ApplicationConfig.RES_INFO_DETAIL,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            if(JSONTool.isStatus(result)){
                                model = JSONTool.jsonDefaluTranClazz(result,null, CultureDetail.class);
                                setData();
                            }else{
                                PromptManager.showToast(JSONTool.errorHint(result));
                            }
                        }else{
                            PromptManager.showToast(R.string.service_error);
                        }
                    }
                });
    }


    private void setData(){
        if(null == model) return;

        back.setText(model.title);
        title.setText(model.title);
        time.setText(addStr(R.string.appear_time,model.pubTime));
        code.setText(addStr(R.string.res_code,model.code));
        author.setText(addStr(R.string.author,model.author));
        type.setText(addStr(R.string.type,model.resClassName));
        publish.setText(addStr(R.string.publishing_unit,model.publishUnit));
        keyword.setText(addStr(R.string.keyword,model.keywords));


        CommonUtil.setTextViewDrawableDirection(chollect,4,
                (model.isCollection == 0)?
                        R.drawable.title_collect_normal:
                        R.drawable.title_collect_select);

        /**
         "total": 8,//图集数量  （图片专有）
         "imgList": [//图片集合 （图片专有）
         {
         "content": "2",//图片描述
         "id": 1,//图片id
         "fixImgUrl": "http://47.92.89.32:8010/atta/data/resource/resinfo/thumb/2017/12/06/d2aef0c7-8656-4684-90ba-761c478044f4_1248x872.jpg" //缩略图
         }......
         ]

         */

        total = model.total;

        List<Roll> imgs = model.imgList;
        setRoll(imgs);

    }

    private void setRoll(final List<Roll> models){
        if(!isRequestList(models)) return;

        List<String> urls = new ArrayList<String>();

        final int size = models.size();

        for (int i=0,j=size;i<j;i++){
            Roll roll = models.get(i);
            urls.add(roll.fixImgUrl);

            if(i == 0){
                String content = roll.content;
                StringBuffer buffer = new StringBuffer(String.valueOf((i +1))).append("/").append(total);
                buffer.append(isRequestStr(content)?
                        content:
                        QXApplication.getContext().getResources().getString(R.string.img_content_empty));

                item_content.setText(buffer.toString());
            }
        }

        convenientBanner.setPages(
                new CBViewHolderCreator<CultureImageHolderView>() {
                    @Override
                    public CultureImageHolderView createHolder() {
                        return new CultureImageHolderView();
                    }
                }, urls)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
//                .setPageIndicator(new int[]{R.drawable.roll_normal, R.drawable.roll_focus})
                //设置指示器的方向
//                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
//                .setOnPageChangeListener(this)//监听翻页事件
                //ViewPager.OnPageChangeListener onPageChangeListener
                .setOnPageChangeListener(new ViewPager.OnPageChangeListener(){

                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }


                    @Override
                    public void onPageSelected(int position) {
                        SystemPrintl.systemPrintl("我现在在改变图片--->>"+position);
                        //滑动完调用
                        if(position >=0 && position < size){
                            Roll roll = models.get(position);
                            String content = roll.content;
                            StringBuffer buffer = new StringBuffer(String.valueOf((position +1))).append("/").append(total);
                            buffer.append(isRequestStr(content)?
                                            content:
                                            QXApplication.getContext().getResources().getString(R.string.img_content_empty));

                            item_content.setText(buffer.toString());

                            if(position > 0){
                                info_linear.setVisibility(View.GONE);
                                CommonUtil.setTextViewDrawableDirection(title_btn,4,R.drawable.res_down_btn);
                            }
                        }

                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
        convenientBanner.notifyDataSetChanged();

//        try {
//            Class cls = Class.forName("com.ToxicBakery.viewpager.transforms."+AccordionTransformer.class.getSimpleName());
//            ABaseTransformer transforemer= (ABaseTransformer)cls.newInstance();
//            convenientBanner.getViewPager().setPageTransformer(true,transforemer);
//
//            //部分3D特效需要调整滑动速度
////            if(transforemerName.equals("StackTransformer")){
////                convenientBanner.setScrollDuration(1200);
////            }
//
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (java.lang.InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
    }

    @Event(value = {R.id.back,R.id.chollect,R.id.share,R.id.title_btn})
    private void viewOnClick(View v) {
        if (model == null && (v != back)) {
            return;
        }
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.chollect:
                if (isUserLogin()) {
                    final int isCollection = model.isCollection;
                    AppHttpRequest.collection(model.id, isCollection, "3", model.title, new AppHttpRequest.OnAppHttpListener() {
                        @Override
                        public void onAppHttpState(boolean isState, String result) {
                            if (isState) {
                                PromptManager.showToast((isCollection == 0) ? R.string.conllection_sucess : R.string.conllection_quit_sucess);
                                model.isCollection = (isCollection == 0) ? 1 : 0;
                                CommonUtil.setTextViewDrawableDirection(chollect, 4, (model.isCollection == 0) ? R.drawable.title_collect_normal : R.drawable.title_collect_select);
                            }
                        }
                    });
                } else {
                    TransformController.transformController(QXApplication.getContext(), LoginActivity.class);
                }
                break;
            case R.id.share:
                mShareAction  =  ShareOtherUtils.shareTool(this,
                        model.shareAddress,
                        model.title,
                        model.content,
                        model.fixImgUrl);
                mShareAction.open();
                break;
            case R.id.title_btn:
                boolean isVisbi = (info_linear.getVisibility() == View.VISIBLE);
                info_linear.setVisibility((isVisbi)?View.GONE:View.VISIBLE);
                CommonUtil.setTextViewDrawableDirection(title_btn,4,((isVisbi)?R.drawable.res_down_btn:R.drawable.res_up_btn));
                break;
        }
    }

    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
    }

    @Override
    public void initViewHandler() {
        if(null != item_content)
            item_content.setMovementMethod(ScrollingMovementMethod.getInstance());
    }
}
